package com.feature.core.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MIME;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * 基于httpclient 的工具类
 * 
 * @Description:
 * @author wangzhiyue
 * @date 2024/06/20 15:13:11
 */
public class HttpClientUtil {
    /** 默认响应超时时间毫秒 */
    public static int SO_TIME_OUT = 10000;
    /** 默认连接超时时间毫秒 */
    public static int CONNECTION_TIME_OUT = 2000;

    private static CloseableHttpClient client = null;
    static {
        HttpClientBuilder builder = HttpClients.custom();
        builder.setMaxConnTotal(50);
        builder.setMaxConnPerRoute(50);
        client = builder.build();
    }

    /**
     * form 表单请求
     * 
     * @param url
     * @param paras
     * @param charset
     * @param connectTime
     * @param timeCout
     * @return
     * @author wangzhiyue
     * @date 2024/06/20 16:11:09
     */
    public static String post(String url, Map<String, String> paras, Charset charset, int connectTime, int timeCout) {
        String r = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (paras != null) {
                for (Map.Entry<String, String> e : paras.entrySet()) {
                    nvps.add(new BasicNameValuePair(e.getKey(), e.getValue()));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));
            RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTime).setSocketTimeout(timeCout).build();
            httpPost.setConfig(config);
            try (CloseableHttpResponse response = client.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                r = EntityUtils.toString(entity, charset);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return r;
    }

    /**
     * json 请求
     * 
     * @param url
     * @param json
     * @param charset
     * @param connectTimeout
     * @param timeCout
     * @return
     * @author wangzhiyue
     * @date 2024/06/20 16:11:29
     */
    public static String postJson(String url, String json, Charset charset, int connectTimeout, int timeCout) {
        String r = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
            RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(timeCout).build();
            httpPost.setConfig(config);
            try (CloseableHttpResponse response = client.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                r = EntityUtils.toString(entity, charset);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return r;
    }

    /**
     * get请求
     * 
     * @param urlvalue
     * @param connectTimeout
     * @param timeCout
     * @return
     * @author wangzhiyue
     * @date 2024/06/20 16:11:58
     */
    public static String get(String urlvalue, Integer connectTimeout, Integer timeCout) {
        String r = "";
        try {
            HttpGet httpGet = new HttpGet(urlvalue);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(timeCout).build();
            httpGet.setConfig(config);
            try (CloseableHttpResponse response = client.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                r = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return r;
    }

    /**
     * get 请求
     * 
     * @param urlvalue
     * @return
     * @author wangzhiyue
     * @date 2024/06/20 16:12:16
     */
    public static String get(String urlvalue) {
        return get(urlvalue, CONNECTION_TIME_OUT, SO_TIME_OUT);
    }

    /**
     * 下载内容
     * 
     * @param urlvalue
     * @return
     * @author wangzhiyue
     * @date 2024/06/20 16:12:35
     */
    public static byte[] download(String urlvalue) {
        byte[] r = null;
        try {
            HttpGet httpGet = new HttpGet(urlvalue);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(CONNECTION_TIME_OUT).setSocketTimeout(SO_TIME_OUT).build();
            httpGet.setConfig(config);
            try (CloseableHttpResponse response = client.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                InputStream infos = entity.getContent();
                System.out.println(infos.available());
                ByteArrayOutputStream bs = new ByteArrayOutputStream(infos.available());
                IOUtils.copy(entity.getContent(), bs);
                r = bs.toByteArray();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return r;
    }

    /***
     * form 表单请求 ，使用utf-8编码
     * 
     * @param urlvalue
     * @param paras
     * @return
     * @author wangzhiyue
     * @date 2024/06/20 16:12:57
     */
    public static String post(String urlvalue, Map<String, String> paras) {
        return post(urlvalue, paras, StandardCharsets.UTF_8, CONNECTION_TIME_OUT, SO_TIME_OUT);
    }

    /**
     * json 请求 ，使用utf-8编码
     * 
     * @param urlvalue
     * @param json
     * @return
     * @author wangzhiyue
     * @date 2024/06/20 16:13:29
     */
    public static String postJson(String urlvalue, String json) {
        return postJson(urlvalue, json, StandardCharsets.UTF_8, CONNECTION_TIME_OUT, SO_TIME_OUT);
    }

    /**
     * 上传文件
     * 
     * @param url
     * @param paras
     * @param charset
     * @param connectTime
     * @param timeCout
     * @param file
     * @return
     * @author wangzhiyue
     * @date 2024/06/20 16:13:50
     */
    public static String postFile(String url, Map<String, String> paras, Charset charset, int connectTime, int timeCout, File file) {
        String r = "";
        try {
            MultipartEntityBuilder builer = MultipartEntityBuilder.create();
            builer.setCharset(MIME.UTF8_CHARSET);
            HttpPost httpPost = new HttpPost(url);
            builer.setMode(HttpMultipartMode.RFC6532);
            if (paras != null) {
                for (Map.Entry<String, String> e : paras.entrySet()) {
                    builer.addTextBody(e.getKey(), e.getValue(), ContentType.TEXT_PLAIN.withCharset(Consts.UTF_8));
                }
            }
            String filetype = file.getName().substring(file.getName().lastIndexOf(".") + 1);
            ContentType contentType = Optional.ofNullable(ContentType.getByMimeType(filetype)).orElse(ContentType.DEFAULT_BINARY.withCharset(Consts.UTF_8));
            builer.addBinaryBody("file", file, contentType, file.getName());
            httpPost.setEntity(builer.build());
            RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTime).setSocketTimeout(timeCout).build();
            httpPost.setConfig(config);
            try (CloseableHttpResponse response = client.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                r = EntityUtils.toString(entity, charset);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return r;
    }

    /**
     * 上传文件 使用utf-8变慢
     * 
     * @param url
     * @param paras
     * @param file
     * @return
     * @author wangzhiyue
     * @date 2024/06/20 16:14:00
     */
    public static String postFile(String url, Map<String, String> paras, File file) {
        return postFile(url, paras, StandardCharsets.UTF_8, CONNECTION_TIME_OUT, CONNECTION_TIME_OUT, file);
    }

    /**
     * 上传字节数组文件
     * 
     * @param url
     * @param paras
     * @param charset
     * @param connectTime
     * @param timeCout
     * @param file
     * @param fileName
     * @return
     * @author wangzhiyue
     * @date 2024/06/20 16:14:15
     */
    public static String postFile(String url, Map<String, String> paras, Charset charset, int connectTime, int timeCout, byte[] file, String fileName) {
        String r = "";
        try {
            MultipartEntityBuilder builer = MultipartEntityBuilder.create();
            builer.setCharset(MIME.UTF8_CHARSET);
            HttpPost httpPost = new HttpPost(url);
            builer.setMode(HttpMultipartMode.RFC6532);
            if (paras != null) {
                for (Map.Entry<String, String> e : paras.entrySet()) {
                    builer.addTextBody(e.getKey(), e.getValue(), ContentType.TEXT_PLAIN.withCharset(Consts.UTF_8));
                }
            }
            builer.addBinaryBody("file", file, ContentType.DEFAULT_BINARY.withCharset(Consts.UTF_8), fileName);
            httpPost.setEntity(builer.build());
            RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTime).setSocketTimeout(timeCout).build();
            httpPost.setConfig(config);
            try (CloseableHttpResponse response = client.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                r = EntityUtils.toString(entity, charset);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return r;
    }

    /**
     * 上传字节数组文件，使用utf-8编码
     * 
     * @param url
     * @param paras
     * @param file
     * @param fileName
     * @return
     * @author wangzhiyue
     * @date 2024/06/20 16:14:53
     */
    public static String postFile(String url, Map<String, String> paras, byte[] file, String fileName) {
        return postFile(url, paras, StandardCharsets.UTF_8, CONNECTION_TIME_OUT, CONNECTION_TIME_OUT, file, fileName);
    }

    public static void main(String[] args) {
        byte[] img = download("https://stplatform.ecej.com/image/bgpicture2.jpg");
        try {
            FileOutputStream out = new FileOutputStream(new File("C:\\Users\\EDY\\Desktop\\work\\1.jpg"));
            IOUtils.write(img, out);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
